package cn.daniellee.plugin.component;

import cn.daniellee.plugin.PlayerChecker;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class LoginChecker implements Listener {


	@EventHandler
	public void onPlayerLogin(PlayerLoginEvent e) {
		if (!PlayerChecker.toggleDefense) PlayerChecker.secondCount++;
		if (PlayerChecker.enableDefense || PlayerChecker.toggleDefense) {
			Player player = e.getPlayer();
			BufferedReader reader = null;
			try {
				List<String> nameList = new ArrayList<>();
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(PlayerChecker.listFile)));
				String temp;
				while ((temp = reader.readLine()) != null) {
					String[] split = temp.split(":");
					nameList.add(split[0]);
				}
				if (nameList.contains(player.getName())) {
					e.allow();
				} else {
					e.disallow(PlayerLoginEvent.Result.KICK_OTHER, Objects.requireNonNull(PlayerChecker.config.getString("disallow-message", "You are not in white list.")));
				}
			} catch (Exception ex) {
				e.disallow(PlayerLoginEvent.Result.KICK_OTHER, Objects.requireNonNull(PlayerChecker.config.getString("error-message", "White list data load error.")));
				PlayerChecker.logger.info("[PlayerChecker]" + PlayerChecker.config.getString("load-error-log", "White list file load error.") + ex.getMessage());
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException ignored) { }
				}
			}
		}
	}

}
